package com.csd.dao;

// default package

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.csd.helper.IConstant;
import com.csd.helper.ProjectState;
import com.csd.pojo.ChangeRecord;
import com.csd.pojo.Project;
import com.csd.pojo.Team;

/**
 * A data access object (DAO) providing persistence and search support for
 * Project entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see .Project
 * @author MyEclipse Persistence Tools
 */

public class ProjectDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(ProjectDAO.class);
	// property constants
	public static final String PROJECTNUM = "projectnum";
	public static final String PROJECTNAME = "projectname";
	public static final String INTRODUCTION = "introduction";
	public static final String STATE = "state";
	public static final String FINALSCORE = "finalscore";
	public static final String LEVEL = "level";
	public static final String CYCLE = "cycle";

	protected void initDao() {
		// do nothing
	}

	public void save(Project transientInstance) {
		log.debug("saving Project instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	
	public void update(Project transientInstance) 
	{
		log.debug("updating Project instance");
		try 
		{
			getHibernateTemplate().saveOrUpdate(transientInstance);
			log.debug("update successful");
		} 
		catch (RuntimeException re) 
		{
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(Project persistentInstance) 
	{
		log.debug("deleting Project instance");
		try 
		{
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Project findById(Integer id) {
		log.debug("getting Project instance with id: " + id);
		try {
			Project instance = (Project) getHibernateTemplate().get(Project.class,
					id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	/**通过老师ID 获得项目的结题申请任务  此时的项目状态应该为结题申请*/
	 @SuppressWarnings("unchecked")
	public List<Project> listFinTaskByTeacherID(Integer teacherID){
	    	List<Project> projects = null;
	    	Object values[] = new Object[]{teacherID, ProjectState.finishApply};
	    	String queryString =" from Project as p where p.teacher.id = ? and p.state = ?";
	   
	    	try {
	    	 	projects = (List<Project>)this.getHibernateTemplate().find(queryString,values);
			} 
	    	catch (Exception e) 
			{
				e.printStackTrace();
			}
	    	return projects;
	    }
	 
	 /*通过老师ID 获得需要评审的申请中的项目任务  此时的项目状态应该为结题申请*/
	 @SuppressWarnings("unchecked")
	public List<Project> listWaitReviewProjectByTeacherID(Integer teacherID)
	 {
		 List<Project> waitReviewProjects = null;
		 Object values[] = new Object[]{teacherID, ProjectState.waitReview};
		 String queryString = "from Project as p where p.teacher.id = ? and p.state = ?";
		 
		 try
		 {
			 waitReviewProjects = (List<Project>)this.getHibernateTemplate().find(queryString, values);
		 }
		 catch(Exception e)
		 {
			 e.printStackTrace();
		 }
		 
		 return waitReviewProjects;
	 }
	
	
	/**通过项目ID查询Team*/
	public Team findTeamByProjectID(Integer id){
		Team team = null;
		String queryString = "select team from Project p where p.id = ?";
		try {
			team = (Team) this.getHibernateTemplate().find(queryString,id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return team;
	}
	
	public List findByExample(Project instance) {
		log.debug("finding Project instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Project instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Project as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) 
		{
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByProjectnum(Object projectnum) 
	{
		return findByProperty(PROJECTNUM, projectnum);
	}

	public List findByProjectname(Object projectname) {
		return findByProperty(PROJECTNAME, projectname);
	}

	public List findByIntroduction(Object introduction) {
		return findByProperty(INTRODUCTION, introduction);
	}

	public List findByState(Object state) {
		return findByProperty(STATE, state);
	}

	public List findByFinalscore(Object finalscore) {
		return findByProperty(FINALSCORE, finalscore);
	}

	public List findByLevel(Object level) {
		return findByProperty(LEVEL, level);
	}

	public List findByCycle(Object cycle) {
		return findByProperty(CYCLE, cycle);
	}

	public List<Project> findByTeam(Integer id) {
		List<Project> pList = null;
		String hql = "from Project as p where p.team.id =?";
		try{
			pList = this.getHibernateTemplate().find(hql,id);
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("=====================");
		}
		return pList;
//		List<Project> projectsList = null;
//		System.out.println(id.toString()+"================="+id);
//		String queryString = "from Project p where p.team.id =?";
//		try {
//			projectsList = this.getHibernateTemplate().find(queryString, id);
//		} catch (Exception e) {
//            e.printStackTrace();
//		}
//		return projectsList;

	}

	public List findAll() {
		log.debug("finding all Project instances");
		try {
			String queryString = "from Project";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Project merge(Project detachedInstance) {
		log.debug("merging Project instance");
		try {
			Project result = (Project) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Project instance) {
		log.debug("attaching dirty Project instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Project instance) {
		log.debug("attaching clean Project instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public void updateProject(Project project) {
		try {
			 this.getHibernateTemplate().saveOrUpdate(project);
		} catch (RuntimeException re) {
			throw re;
		}
       
	}

	public static ProjectDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ProjectDAO) ctx.getBean("ProjectDAO");
	}
	
	/**
	 * 查询正在开发中的项目
	 * @return 
	 */
	public List<Project> listDevelopingProject() {
        log.debug("find developing project of manager");
        List<Project> resultsList = null;
        try {
        	String hqlString = "from Project as model where state = '"+ProjectState.prophasePass
        		+"' or state = '"+ProjectState.metaphase +"' or state = '"+ProjectState.metaphaseEnd 
        		+"' or state = '"+ProjectState.finishApply +"' or state = '"+ProjectState.telophasePass +"'";
            resultsList = getHibernateTemplate().find(hqlString);
            log.debug("finding successful");
        } catch (RuntimeException re) {
            log.error("finding failed", re);
            throw re;
        }
        return resultsList;
    }
	
//	/**
//	 * 查询管理员对应阶段未处理的项目申请
//	 * @return 
//	 */
//	public List<ChangeRecord> listUnhandleCROfManager() {
//        log.debug("find unhandle project of manager");
//        List<ChangeRecord> resultsList = null;
//        try {
//        	String hqlString = "from ChangeRecord as model where result = "+IConstant.changeRecordPass
//        		+" and state = "+IConstant.managerUnhandle;
//            resultsList = getHibernateTemplate().find(hqlString);
//            log.debug("finding successful");
//        } catch (RuntimeException re) {
//            log.error("finding failed", re);
//            throw re;
//        }
//        return resultsList;
//    }
}